import 'package:craze/common/index.dart';
import 'package:craze/models/team_model.dart';
import 'package:craze/models/user_model.dart';
import 'package:craze/services/chat_service.dart';
import 'package:craze/services/service_locator.dart';
import 'package:craze/services/team_service.dart';
import 'package:craze/services/user_service.dart';
import 'package:craze/stores/auth_store.dart';
import 'package:craze/stores/collection_store.dart';
import 'package:craze/stores/team_store.dart';
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';

class TeamView extends StatefulWidget {
  const TeamView({super.key});

  @override
  State<TeamView> createState() => _TeamViewState();
}

class _TeamViewState extends State<TeamView> {
  // 获取所需的服务和存储
  final TeamStore _teamStore = getIt<TeamStore>();
  final TeamService _teamService = getIt<TeamService>();
  final UserService _userService = getIt<UserService>();
  final AuthStore _authStore = getIt<AuthStore>();
  final CollectionStore _collectionStore = getIt<CollectionStore>();

  // 关注状态缓存
  final Map<String, bool> _followStatus = {};

  // 选中的用户列表（用于邀请弹窗）
  final Set<String> _selectedUserIds = {};

  TeamModel? get _currentTeam => _teamStore.selectedTeam;

  // 收藏状态
  bool _isTeamCollected = false;

  @override
  void initState() {
    super.initState();

    // 初始化关注状态
    _initFollowStatus();

    // 初始化收藏状态
    _checkCollectionStatus();
  }

  // 检查当前团队的收藏状态
  void _checkCollectionStatus() {
    if (_authStore.isLoggedIn &&
        _authStore.currentUser != null &&
        _currentTeam != null) {
      setState(() {
        _isTeamCollected = _collectionStore.isTeamInCollection(
          _currentTeam!.id,
        );
      });
    }
  }

  // 切换团队收藏状态
  Future<void> _toggleTeamCollection() async {
    if (!_authStore.isLoggedIn || _authStore.currentUser == null) {
      _showLoginDialog();
      return;
    }

    if (_currentTeam == null) return;

    try {
      // 立即更新UI以提供即时反馈
      setState(() {
        _isTeamCollected = !_isTeamCollected;
      });

      // 调用服务切换收藏状态
      await _collectionStore.toggleTeamCollection(_currentTeam!.id);
    } catch (e) {
      // 发生错误时恢复状态
      setState(() {
        _isTeamCollected = !_isTeamCollected;
      });

      // 显示错误提示
      MyToast.showError(
        context,
        "Failed to update collection: ${e.toString()}",
      );
    }
  }

  // 初始化关注状态
  void _initFollowStatus() {
    if (_authStore.isLoggedIn &&
        _authStore.currentUser != null &&
        _currentTeam != null) {
      // 获取团队所有成员
      for (final memberId in _currentTeam!.memberIds) {
        // 设置关注状态
        _followStatus[memberId] = _authStore.currentUser!.followingIds.contains(
          memberId,
        );
      }
    }
  }

  // 关注/取消关注用户
  Future<void> _toggleFollowUser(String userId) async {
    if (!_authStore.isLoggedIn || _authStore.currentUser == null) {
      _showLoginDialog();
      return;
    }

    final currentUserId = _authStore.currentUser!.id;

    // 判断当前是否已关注
    bool isFollowed = _followStatus[userId] ?? false;

    try {
      setState(() {
        // 立即更新UI状态，提供即时反馈
        _followStatus[userId] = !isFollowed;
      });

      if (isFollowed) {
        // 取消关注
        await _userService.unfollowUser(currentUserId, userId);
      } else {
        // 关注
        await _userService.followUser(currentUserId, userId);
      }

      // 刷新登录用户信息以获取最新的关注列表
      _authStore.currentUser = _userService.getUserById(currentUserId);
    } catch (e) {
      // 如果出错，恢复原状态
      setState(() {
        _followStatus[userId] = isFollowed;
      });

      // 显示错误提示
      if (mounted) {
        MyToast.showError(context, e.toString());
      }
    }
  }

  // 邀请成员
  void _inviteMember() {
    if (!_authStore.isLoggedIn || _authStore.currentUser == null) {
      _showLoginDialog();
      return;
    }

    // 清空之前选中的用户
    _selectedUserIds.clear();

    // 获取当前用户关注的用户列表
    final followingUsers = _getFollowingUsers();

    // 过滤掉已经在团队中的成员
    final filteredUsers =
        followingUsers
            .where(
              (user) =>
                  _currentTeam != null &&
                  !_currentTeam!.memberIds.contains(user.id),
            )
            .toList();

    // 显示邀请弹窗（居中显示）
    showDialog(
      context: context,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return Dialog(
              backgroundColor: Colors.transparent,
              insetPadding: EdgeInsets.symmetric(horizontal: 40.w),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  _buildInviteDialog(filteredUsers, setState),

                  SizedBox(height: 20.h),

                  Row(
                    children: [
                      // 取消按钮
                      Expanded(
                        child: GestureDetector(
                          onTap: () {
                            Navigator.pop(context);
                          },
                          child: Container(
                            height: 52.h,
                            decoration: BoxDecoration(
                              color: Colors.grey.withAlpha(0),
                              borderRadius: BorderRadius.circular(25.r),
                              border: Border.all(
                                color: Colors.white,
                                width: 1.w,
                              ),
                            ),
                            alignment: Alignment.center,
                            child: Text(
                              'Cancel',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 16.sp,
                                fontWeight: FontWeight.w400,
                                fontFamily:
                                    GoogleFonts.mochiyPopOne().fontFamily,
                              ),
                            ),
                          ),
                        ),
                      ),

                      SizedBox(width: 20.w),

                      // 邀请按钮
                      Expanded(
                        child: GestureDetector(
                          onTap: () async {
                            if (_selectedUserIds.isEmpty) {
                              MyToast.showInfo(
                                context,
                                "Please select users to invite",
                              );
                              return;
                            }

                            if (_currentTeam != null) {
                              // 关闭弹窗
                              Navigator.pop(context);

                              // 邀请用户
                              await _sendTeamInvites();
                            }
                          },
                          child: Container(
                            height: 52.h,
                            decoration: BoxDecoration(
                              color: MyColors.blue,
                              borderRadius: BorderRadius.circular(25.r),
                            ),
                            alignment: Alignment.center,
                            child: Text(
                              'Invite',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 16.sp,
                                fontWeight: FontWeight.w400,
                                fontFamily:
                                    GoogleFonts.mochiyPopOne().fontFamily,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            );
          },
        );
      },
    );
  }

  // 获取当前用户关注的用户列表
  List<UserModel> _getFollowingUsers() {
    if (!_authStore.isLoggedIn || _authStore.currentUser == null) {
      return [];
    }

    final followingIds = _authStore.currentUser!.followingIds;
    final users = <UserModel>[];

    for (final id in followingIds) {
      final user = _userService.getUserById(id);
      if (user != null) {
        users.add(user);
      }
    }

    return users;
  }

  // 构建邀请弹窗
  Widget _buildInviteDialog(List<UserModel> users, StateSetter setState) {
    return Container(
      width: double.infinity,
      height: 0.5.sh,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment(0.50, -0.00),
            end: Alignment(0.50, 0.68),
            colors: [const Color(0x33026CE6), Colors.transparent],
          ),
          borderRadius: BorderRadius.circular(12.r),
        ),
        child: Column(
          children: [
            // 顶部间距
            SizedBox(height: 20.h),

            // 用户列表（选择区域）
            Expanded(
              child:
                  users.isEmpty
                      ? Center(
                        child: Text(
                          'No users to invite',
                          style: TextStyle(color: Colors.black),
                        ),
                      )
                      : ListView.builder(
                        itemCount: users.length,
                        padding: EdgeInsets.symmetric(
                          horizontal: 20.w,
                          vertical: 10.h,
                        ),
                        itemBuilder: (context, index) {
                          final user = users[index];
                          final isSelected = _selectedUserIds.contains(user.id);

                          return Padding(
                            padding: EdgeInsets.symmetric(vertical: 10.h),
                            child: GestureDetector(
                              onTap: () {
                                setState(() {
                                  if (isSelected) {
                                    _selectedUserIds.remove(user.id);
                                  } else {
                                    _selectedUserIds.add(user.id);
                                  }
                                });
                              },
                              child: Row(
                                children: [
                                  // 用户头像
                                  CircleAvatar(
                                    radius: 25.r,
                                    backgroundImage: AssetImage(user.avatar),
                                  ),
                                  SizedBox(width: 15.w),
                                  // 用户名
                                  Expanded(
                                    child: Text(
                                      user.name,
                                      style: TextStyle(
                                        color: Colors.black,
                                        fontSize: 14.sp,
                                        fontFamily:
                                            GoogleFonts.mochiyPopOne()
                                                .fontFamily,
                                        fontWeight: FontWeight.w400,
                                      ),
                                    ),
                                  ),
                                  // 选择圆圈
                                  Container(
                                    width: 24.w,
                                    height: 24.w,
                                    decoration: BoxDecoration(
                                      shape: BoxShape.circle,
                                      color:
                                          isSelected
                                              ? MyColors.blue
                                              : MyColors.white,
                                      border: Border.all(
                                        color: Colors.grey.shade300,
                                        width: 2.w,
                                      ),
                                    ),
                                    child:
                                        isSelected
                                            ? Icon(
                                              Icons.check,
                                              color: Colors.white,
                                              size: 18.sp,
                                            )
                                            : null,
                                  ),
                                ],
                              ),
                            ),
                          );
                        },
                      ),
            ),

            // 底部间距
            SizedBox(height: 20.h),
          ],
        ),
      ),
    );
  }

  // 发送团队邀请
  Future<void> _sendTeamInvites() async {
    try {
      if (_currentTeam == null || _selectedUserIds.isEmpty) {
        return;
      }

      // 获取ChatService实例
      final chatService = getIt<ChatService>();

      // 向每个选中的用户发送私聊邀请
      for (final userId in _selectedUserIds) {
        // 查找或创建与该用户的私聊
        final chat = await chatService.findOrCreatePrivateChat(
          _authStore.currentUser!.id,
          userId,
        );

        // 发送团队邀请消息
        await chatService.sendMessage(
          chatId: chat.id,
          senderId: _authStore.currentUser!.id,
          content:
              "I would like to invite you to join our diving team: ${_currentTeam!.name}",
          isTeamInvite: true,
          teamId: _currentTeam!.id,
        );
      }

      // 显示成功提示
      MyToast.showSuccess(context, "Invitations sent successfully");

      // 清空选中的用户列表
      _selectedUserIds.clear();
    } catch (e) {
      // 显示错误提示
      MyToast.showError(context, "Failed to send invitations: ${e.toString()}");
    }
  }

  // 显示登录提示对话框
  void _showLoginDialog() {
    // 获取当前页面的完整路径，包括查询参数
    final currentPath = GoRouterState.of(context).uri.toString();

    LoginDialog.show(
      context,
      title: 'Login',
      description: 'Please login to use this feature',
      returnPath: currentPath, // 显式传递当前路径作为返回路径
    );
  }

  // 检查当前用户是否已加入团队
  bool _isUserInTeam() {
    if (!_authStore.isLoggedIn ||
        _authStore.currentUser == null ||
        _currentTeam == null) {
      return false;
    }

    return _currentTeam!.memberIds.contains(_authStore.currentUser!.id);
  }

  // 加入团队
  Future<void> _joinTeam() async {
    if (!_authStore.isLoggedIn || _authStore.currentUser == null) {
      _showLoginDialog();
      return;
    }

    if (_currentTeam == null) return;

    // 检查团队是否已满
    if (_currentTeam!.isFull()) {
      MyToast.showInfo(context, "The team is already full");
      return;
    }

    // 检查用户是否已在团队中
    if (_isUserInTeam()) {
      MyToast.showInfo(context, "You are already a member of this team");
      return;
    }

    try {
      // 调用团队服务加入团队
      final success = await _teamService.joinTeam(
        _currentTeam!.id,
        _authStore.currentUser!.id,
      );

      if (success) {
        // 重新加载团队数据
        await _teamStore.loadTeams();
        _teamStore.selectTeam(_currentTeam!.id);

        // 显示成功提示
        MyToast.showSuccess(context, "Successfully joined the team");

        // 如果团队有群聊，将用户添加到群聊中
        if (_currentTeam!.chatId.isNotEmpty) {
          _addUserToGroupChat();
        }

        // 刷新界面
        setState(() {});
      } else {
        MyToast.showError(context, "Failed to join the team");
      }
    } catch (e) {
      // 显示错误提示
      MyToast.showError(context, "Error joining team: ${e.toString()}");
    }
  }

  // 添加用户到团队群聊
  Future<void> _addUserToGroupChat() async {
    if (!_authStore.isLoggedIn ||
        _authStore.currentUser == null ||
        _currentTeam == null) {
      return;
    }

    if (_currentTeam!.chatId.isEmpty) return;

    try {
      // 获取ChatService实例
      final chatService = getIt<ChatService>();

      // 获取群聊
      final chat = chatService.getChatById(_currentTeam!.chatId);
      if (chat != null) {
        // 检查用户是否已在群聊中
        if (!chat.participantIds.contains(_authStore.currentUser!.id)) {
          // 添加用户到群聊参与者列表
          chat.participantIds.add(_authStore.currentUser!.id);
          await chatService.updateChat(chat);

          // 发送加入消息
          await chatService.sendMessage(
            chatId: chat.id,
            senderId: _authStore.currentUser!.id,
            content: "Hello everyone! I just joined the team.",
          );
        }
      }
    } catch (e) {
      print("Error adding user to group chat: ${e.toString()}");
    }
  }

  // 打开团队群聊
  void _openGroupChat() {
    if (!_authStore.isLoggedIn || _authStore.currentUser == null) {
      _showLoginDialog();
      return;
    }

    if (_currentTeam == null || _currentTeam!.chatId.isEmpty) {
      MyToast.showInfo(context, "This team doesn't have a group chat");
      return;
    }

    // 检查用户是否在团队中
    if (!_isUserInTeam()) {
      MyToast.showInfo(context, "You need to join the team first");
      return;
    }

    // 导航到聊天页面
    GoRouter.of(context).push('/chat/${_currentTeam!.chatId}');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: 1.sw,
        height: 1.sh,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(MyImages.commonBg),
            fit: BoxFit.cover,
          ),
        ),
        child: Observer(
          builder: (_) {
            if (_teamStore.selectedTeam == null) {
              return Center(child: CircularProgressIndicator());
            }

            final team = _teamStore.selectedTeam!;
            final isUserInTeam = _isUserInTeam();

            // 每次团队更新时重新检查收藏状态
            if (_authStore.isLoggedIn && _authStore.currentUser != null) {
              _isTeamCollected = _collectionStore.isTeamInCollection(team.id);
            }

            return SafeArea(
              top: false,
              bottom: false,
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    AspectRatio(
                      aspectRatio: 1 / 1,
                      child: Container(
                        decoration: BoxDecoration(
                          image: DecorationImage(
                            image: AssetImage(MyImages.teamBg),
                            fit: BoxFit.cover,
                          ),
                        ),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            SizedBox(height: 56.h),
                            Padding(
                              padding: EdgeInsets.symmetric(horizontal: 20.w),
                              child: Row(
                                children: [
                                  GestureDetector(
                                    onTap: () {
                                      // 使用 Navigator.canPop 检查是否可以安全返回
                                      if (Navigator.canPop(context)) {
                                        GoRouter.of(context).pop();
                                      } else {
                                        // 如果不能返回，导航到首页
                                        GoRouter.of(context).go('/');
                                      }
                                    },
                                    child: Icon(
                                      MyIcons.iconBack,
                                      color: Colors.white,
                                      size: 24.sp,
                                    ),
                                  ),
                                  Expanded(
                                    child: Center(
                                      child: Text(
                                        'Diving Team',
                                        style: TextStyle(
                                          color: Colors.white,
                                          fontSize: 22.sp,
                                          fontWeight: FontWeight.w400,
                                          fontFamily:
                                              GoogleFonts.mochiyPopOne()
                                                  .fontFamily,
                                        ),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),

                            const Spacer(),

                            Container(
                              width: 1.sw,
                              decoration: BoxDecoration(
                                gradient: LinearGradient(
                                  begin: Alignment.topCenter,
                                  end: Alignment.bottomCenter,
                                  colors: [
                                    Colors.transparent,
                                    Colors.black.withAlpha(178),
                                  ],
                                ),
                              ),
                              padding: EdgeInsets.symmetric(horizontal: 20.w),
                              child: Row(
                                children: [
                                  Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      SizedBox(
                                        width: 0.8.sw,
                                        child: Text(
                                          team.name,
                                          style: TextStyle(
                                            color: Colors.white,
                                            fontSize: 22.sp,
                                            fontFamily:
                                                GoogleFonts.mochiyPopOne()
                                                    .fontFamily,
                                            fontWeight: FontWeight.w400,
                                          ),
                                          maxLines: 5,
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                      ),
                                      SizedBox(height: 16.h),

                                      // 获取发起者姓名
                                      Text(
                                        'initiator:${_getUserName(team.initiatorId)}',
                                        style: TextStyle(
                                          color: Colors.white,
                                          fontSize: 14.sp,
                                          fontFamily:
                                              GoogleFonts.inter().fontFamily,
                                          fontWeight: FontWeight.w400,
                                          height: 1.43,
                                          shadows: [
                                            Shadow(
                                              offset: Offset(0, 4),
                                              blurRadius: 4,
                                              color: Color(
                                                0xFF000000,
                                              ).withOpacity(0.25),
                                            ),
                                          ],
                                        ),
                                      ),

                                      Text(
                                        'Departure date:${_formatDate(team.departureDate)}',
                                        style: TextStyle(
                                          color: Colors.white,
                                          fontSize: 14.sp,
                                          fontFamily:
                                              GoogleFonts.inter().fontFamily,
                                          fontWeight: FontWeight.w400,
                                          height: 1.43,
                                        ),
                                      ),

                                      Text(
                                        'Number of people:${team.memberIds.length}/${team.maxMembers}',
                                        style: TextStyle(
                                          color: Colors.white,
                                          fontSize: 14.sp,
                                          fontFamily:
                                              GoogleFonts.inter().fontFamily,
                                          fontWeight: FontWeight.w400,
                                          height: 1.43,
                                        ),
                                      ),
                                    ],
                                  ),
                                  const Spacer(),
                                  Align(
                                    alignment: Alignment.bottomCenter,
                                    child: Padding(
                                      padding: EdgeInsets.only(bottom: 10.h),
                                      child: GestureDetector(
                                        onTap: _toggleTeamCollection,
                                        child: Container(
                                          width: 37.w,
                                          height: 37.w,
                                          decoration: BoxDecoration(
                                            color: Colors.white.withAlpha(50),
                                            shape: BoxShape.circle,
                                          ),
                                          child: Icon(
                                            _isTeamCollected
                                                ? MyIcons.iconCollectFill
                                                : MyIcons.iconCollect,
                                            color:
                                                _isTeamCollected
                                                    ? Colors.red
                                                    : Colors.white,
                                            size: 24.sp,
                                          ),
                                        ),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),

                    SizedBox(height: 20.h),

                    // 团队简介
                    Padding(
                      padding: EdgeInsets.symmetric(horizontal: 20.w),
                      child: Text(
                        team.description,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 18.sp,
                          fontFamily: GoogleFonts.inter().fontFamily,
                          fontWeight: FontWeight.w400,
                          height: 1.39,
                        ),
                      ),
                    ),

                    SizedBox(height: 20.h),

                    // 团队成员
                    Padding(
                      padding: EdgeInsets.symmetric(horizontal: 20.w),
                      child: Container(
                        width: double.infinity,
                        decoration: BoxDecoration(
                          color: MyColors.cardDark,
                          borderRadius: BorderRadius.circular(12.r),
                        ),
                        padding: EdgeInsets.symmetric(vertical: 16.h),
                        child: Column(
                          children: [
                            Text(
                              'Team members',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 12.sp,
                                fontFamily:
                                    GoogleFonts.mochiyPopOne().fontFamily,
                                fontWeight: FontWeight.w400,
                                height: 1,
                              ),
                            ),
                            SizedBox(height: 16.h),
                            // 团队成员列表
                            _buildTeamMembers(team),
                          ],
                        ),
                      ),
                    ),

                    // 添加底部按钮（Join In 和 Group Chat）
                    Padding(
                      padding: EdgeInsets.symmetric(
                        horizontal: 20.w,
                        vertical: 30.h,
                      ),
                      child: Row(
                        children: [
                          // Join In 按钮
                          Expanded(
                            child: GestureDetector(
                              onTap: () {
                                // 已经是团队成员则不执行操作
                                if (isUserInTeam) {
                                  MyToast.showInfo(
                                    context,
                                    "You are already a member of this team",
                                  );
                                } else {
                                  _joinTeam();
                                }
                              },
                              child: Container(
                                height: 48.h,
                                decoration: BoxDecoration(
                                  color: MyColors.blue,
                                  borderRadius: BorderRadius.circular(24.r),
                                ),
                                alignment: Alignment.center,
                                child: Text(
                                  'Join In',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 16.sp,
                                    fontWeight: FontWeight.w600,
                                    fontFamily:
                                        GoogleFonts.mochiyPopOne().fontFamily,
                                  ),
                                ),
                              ),
                            ),
                          ),

                          SizedBox(width: 16.w),

                          // Group Chat 按钮
                          Expanded(
                            child: GestureDetector(
                              onTap: () {
                                // 只有团队成员可以进入群聊
                                _openGroupChat();
                              },
                              child: Container(
                                height: 48.h,
                                decoration: BoxDecoration(
                                  color:
                                      isUserInTeam
                                          ? MyColors.blue.withOpacity(0.8)
                                          : MyColors.blue.withOpacity(
                                            0.3,
                                          ), // 未加入团队时按钮颜色变暗
                                  borderRadius: BorderRadius.circular(24.r),
                                ),
                                alignment: Alignment.center,
                                child: Text(
                                  'Group Chat',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 16.sp,
                                    fontWeight: FontWeight.w600,
                                    fontFamily:
                                        GoogleFonts.mochiyPopOne().fontFamily,
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            );
          },
        ),
      ),
    );
  }

  // 日期格式化
  String _formatDate(DateTime date) {
    return "${date.month}/${date.day}";
  }

  // 获取用户名
  String _getUserName(String userId) {
    final user = _userService.getUserById(userId);
    return user?.name ?? "Unknown";
  }

  // 获取用户头像
  String _getUserAvatar(String userId) {
    final user = _userService.getUserById(userId);
    return user?.avatar ?? MyImages.touxiang1;
  }

  // 构建团队成员列表
  Widget _buildTeamMembers(TeamModel team) {
    // 团队成员最多6个人，显示在一排
    List<Widget> memberWidgets = [];

    // 添加已有成员
    for (int i = 0; i < team.memberIds.length; i++) {
      memberWidgets.add(
        _buildTeamMember(
          userId: team.memberIds[i],
          isFollowed: _followStatus[team.memberIds[i]] ?? false,
          onFollow: () => _toggleFollowUser(team.memberIds[i]),
        ),
      );
    }

    // 添加空位置（用于邀请）
    for (int i = team.memberIds.length; i < team.maxMembers; i++) {
      memberWidgets.add(_buildEmptySlot());
    }

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 10.w),
      child: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: Row(
          children:
              memberWidgets.map((widget) {
                return Padding(
                  padding: EdgeInsets.symmetric(horizontal: 8.w),
                  child: widget,
                );
              }).toList(),
        ),
      ),
    );
  }

  // 构建团队成员卡片
  Widget _buildTeamMember({
    required String userId,
    required bool isFollowed,
    required VoidCallback onFollow,
  }) {
    return Column(
      children: [
        // 头像
        GestureDetector(
          onTap: () {
            GoRouter.of(
              context,
            ).push(AppRouter.otherProfile, extra: {'userId': userId});
          },
          child: Container(
            width: 56.w,
            height: 56.h,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(_getUserAvatar(userId)),
                fit: BoxFit.cover,
              ),
              shape: BoxShape.circle,
            ),
          ),
        ),

        SizedBox(height: 10.h),

        // 用户名
        Text(
          _getUserName(userId),
          style: TextStyle(
            color: Colors.white,
            fontSize: 12.sp,
            fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
            fontWeight: FontWeight.w400,
            height: 1,
          ),
        ),

        SizedBox(height: 4.h),

        // 关注按钮
        GestureDetector(
          onTap: onFollow,
          child: Container(
            width: 56.w,
            height: 18.h,
            decoration: ShapeDecoration(
              gradient:
                  isFollowed
                      ? null
                      : LinearGradient(
                        begin: Alignment(0.50, 0.00),
                        end: Alignment(0.50, 0.86),
                        colors: [
                          const Color(0xFF0076FF),
                          const Color(0xFF045EC6),
                        ],
                      ),
              color: isFollowed ? Colors.grey : null,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12.r),
              ),
            ),
            child: Center(
              child: Text(
                isFollowed ? 'Unfollow' : 'follow',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 11.sp,
                  fontWeight: FontWeight.w400,
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  // 构建空位置（用于邀请）
  Widget _buildEmptySlot() {
    return GestureDetector(
      onTap: _inviteMember, // 点击整个空位置触发邀请弹窗
      child: Column(
        children: [
          // 加号图标
          Container(
            width: 56.w,
            height: 56.h,
            decoration: BoxDecoration(
              color: Colors.black.withOpacity(0.3),
              shape: BoxShape.circle,
            ),
            child: Icon(Icons.add, color: Colors.white, size: 30.sp),
          ),

          SizedBox(height: 10.h),

          // 问号文本
          Text(
            '???',
            style: TextStyle(
              color: Colors.white,
              fontSize: 12.sp,
              fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
              fontWeight: FontWeight.w400,
              height: 1,
            ),
          ),

          SizedBox(height: 4.h),

          // 邀请按钮
          GestureDetector(
            onTap: _inviteMember,
            child: Container(
              width: 56.w,
              height: 18.h,
              decoration: ShapeDecoration(
                gradient: LinearGradient(
                  begin: Alignment(0.50, 0.00),
                  end: Alignment(0.50, 0.86),
                  colors: [const Color(0xFF0076FF), const Color(0xFF045EC6)],
                ),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12.r),
                ),
              ),
              child: Center(
                child: Text(
                  'invite',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 11.sp,
                    fontWeight: FontWeight.w400,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
